package com.shopmall.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopmall.system.dao.RoleMapper;
import com.shopmall.system.dao.RoleMenuMapper;
import com.shopmall.system.entity.Role;
import com.shopmall.system.entity.RoleMenu;
import com.shopmall.system.service.IRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    RoleMenuMapper roleMenuMapper;
    @Override
    public IPage<Role> pageList(Role role) {
        IPage<Role> page = new Page<>(role.getPageNum(),role.getPageSize());
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        IPage<Role> roleIPage = this.baseMapper.selectPage(page, wrapper);
        if(role.getId()!=null){
            roleIPage.getRecords().forEach(item->{
                item.setMenus(roleMenuMapper.selectList(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRid,item.getId())).stream().map(RoleMenu::getMid).toList());
            });
        }
        //拼接sql，sql之后添加指定的语句
        return roleIPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addOrUpdateRole(Role role) {
        int num=0;
        if(role.getId()==null){
            num = this.baseMapper.insert(role);
            if(role.getMenus()!=null){
                for (Integer menu : role.getMenus()) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setMid(menu);
                    roleMenu.setRid(role.getId());
                    roleMenuMapper.insert(roleMenu);
                }

            }
        }else{
            roleMenuMapper.delete(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRid,role.getId()));
            num = this.baseMapper.updateById(role);
        }
        return num;
    }

    @Override
    public int deleteRoleById(Integer id) {
        return this.baseMapper.deleteById(id);
    }

}
